//用户状态管理

import { createSlice } from "@reduxjs/toolkit";
import { removeToken } from "@/utils";
import { setToken as _setToken, getToken } from "@/utils";
import { loginAPI, userProfileAPI } from "@/apis/user";

const userStore = createSlice({
  name: 'user',
  initialState: {
    token: getToken() || '',
    userInfo: {}

  },
  reducers: {
    setToken(state, action) {
      state.token = action.payload
      _setToken(action.payload)
    },
    setUserInfo(state, action) {
      state.userInfo = action.payload
    },
    clearUserInfo(state) {
      state.token = ''
      state.userInfo = {}
      removeToken()
    }
  }
})

const { setToken, setUserInfo, clearUserInfo } = userStore.actions
const userReduer = userStore.reducer

//异步方法，完成登录获取Token
const fetchLogin = (loginForm) => {
  return async (dispatch) => {
    const res = await loginAPI(loginForm)
    dispatch(setToken(res.data.token))
  }
}
//用户个人信息获取
const fetchUserInfo = () => {
  return async (dispatch) => {
    const res = await userProfileAPI()
    dispatch(setUserInfo(res.data))
  }
}
export { setToken, fetchLogin, fetchUserInfo, clearUserInfo }

export default userReduer